﻿using System;
using System.Net;
using LIK.WakeOnLan.Network;

namespace LIK.WakeOnLan.Code
{

    internal class WolCommand
    {
        internal static void SendWakUpOnLanMessage(NetworkClient nClient)
        {
            using (var client = new WolClient())
            {
                try
                {
                    
                    //WOL packet is sent over UDP 255.255.255.0:40000.
                    client.Connect(IPAddress.Broadcast, nClient.Port); //nClient.BroadCastIpAddress
                    //client.Connect(new IPAddress(0xffffffff),  //255.255.255.255  i.e broadcast
                    //   0x2fff); // port=12287 let's use this one 
                    client.SetClientToBrodcastMode();

                    byte[] wolpacket = GetWolPacket(nClient.MacAddresInBytes);

                    //now send wake up packet
                    int reternedValue = client.Send(wolpacket, wolpacket.Length); //, new IPEndPoint( nClient.GetIpAddress(), 0x1));
                    client.Close();
                }
                catch 
                {
                    
                }
            }

        }

        private static byte[] GetWolPacket(byte[] macAddress, byte[] password = null)
        {
            if (macAddress == null)
                throw new Exception("macAddress");
            if (macAddress.Length != 6)
                throw new Exception("Wrong mac address length");
            if (password != null && password.Length != 6)
            {
                throw new ArgumentException("Wrong IP address length");
            }

            var packet = password != null ? new byte[18 * 6] : new byte[17 * 6];

            int offset, i;
            for (offset = 0; offset < 6; ++offset)
            {
                packet[offset] = 0xFF;
            }

            for (offset = 6; offset < 17*6; offset += 6)
            {
                for (i = 0; i < 6; ++i)
                {
                    packet[i + offset] = macAddress[i];
                }
            }
            if (password != null)
            {
                for (offset = 16*6 + 6; offset < 18*6; offset += 6)
                {
                    for (i = 0; i < 6; ++i)
                    {
                        packet[i + offset] = password[i];
                    }
                }
            }
            return packet;
        }



    }
}
